#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据库初始化和虚拟数据生成脚本
用于创建测试数据，方便开发和演示
"""

import sys
import os
from datetime import date, datetime, timedelta
from faker import Faker
from sqlalchemy.orm import Session
from database import SessionLocal, init_db, reset_db
from models import User, Work, Contest, AITool, WeChatQR
from auth import get_password_hash
import random
import uuid

# 创建Faker实例（中文）
fake = Faker('zh_CN')

def create_sample_users(db: Session, count: int = 20):
    """
    创建示例用户
    
    Args:
        db: 数据库会话
        count: 创建用户数量
    """
    print(f"正在创建 {count} 个示例用户...")
    
    users = []
    
    # 创建管理员用户
    admin_user = User(
        username="admin",
        email="admin@aihub.com",
        hashed_password=get_password_hash("admin123"),
        nickname="系统管理员",
        avatar="/img/thumb.jpg",
        is_active=True,
        is_verified=True
    )
    users.append(admin_user)
    
    # 创建测试用户
    test_user = User(
        username="testuser",
        email="test@aihub.com",
        hashed_password=get_password_hash("test123"),
        nickname="测试用户",
        avatar="/img/thumb.jpg",
        is_active=True,
        is_verified=True
    )
    users.append(test_user)
    
    # 创建随机用户
    for i in range(count - 2):
        username = f"user_{i+1:03d}"
        # 确保邮箱唯一性
        email = f"user_{i+1:03d}@example.com"
        user = User(
            username=username,
            email=email,
            hashed_password=get_password_hash("password123"),
            nickname=fake.name(),
            avatar="/img/thumb.jpg",
            is_active=True,
            is_verified=random.choice([True, False])
        )
        
        # 部分用户添加微信信息
        if random.random() < 0.3:  # 30%的用户有微信登录
            user.wechat_openid = f"wx_openid_{uuid.uuid4().hex[:12]}"
        
        users.append(user)
    
    # 批量添加到数据库
    db.add_all(users)
    db.commit()
    
    print(f"成功创建 {len(users)} 个用户")
    return users

def create_sample_works(db: Session, users: list, count: int = 100):
    """
    创建示例作品
    
    Args:
        db: 数据库会话
        users: 用户列表
        count: 创建作品数量
    """
    print(f"正在创建 {count} 个示例作品...")
    
    categories = ["image", "video", "music", "text"]
    
    # 预定义的作品标题和描述模板
    image_titles = [
        "AI生成的梦幻风景", "未来城市概念图", "抽象艺术作品", "人物肖像画", "科幻场景插画",
        "自然风光摄影", "建筑设计图", "动漫角色设计", "产品概念图", "数字艺术作品"
    ]
    
    video_titles = [
        "AI动画短片", "产品宣传视频", "教学演示视频", "创意广告片", "纪录片片段",
        "音乐MV", "游戏预告片", "科普动画", "艺术实验视频", "生活记录片"
    ]
    
    music_titles = [
        "AI作曲实验", "电子音乐作品", "古典音乐改编", "流行歌曲创作", "背景音乐",
        "游戏音效", "冥想音乐", "爵士乐即兴", "摇滚乐作品", "民族音乐融合"
    ]
    
    text_titles = [
        "AI写作实验", "科幻小说片段", "诗歌创作", "技术文档", "创意故事",
        "学术论文", "新闻报道", "产品说明", "用户手册", "创意文案"
    ]
    
    title_templates = {
        "image": image_titles,
        "video": video_titles,
        "music": music_titles,
        "text": text_titles
    }
    
    # 常用标签
    common_tags = {
        "image": ["AI绘画", "数字艺术", "概念设计", "插画", "摄影", "设计", "创意", "艺术"],
        "video": ["AI视频", "动画", "短片", "创意", "教学", "娱乐", "艺术", "技术"],
        "music": ["AI音乐", "电子", "古典", "流行", "实验", "背景音乐", "原创", "编曲"],
        "text": ["AI写作", "创意", "文学", "技术", "教育", "新闻", "故事", "诗歌"]
    }
    
    works = []
    
    for i in range(count):
        category = random.choice(categories)
        user = random.choice(users)
        
        # 选择标题
        title = random.choice(title_templates[category])
        if random.random() < 0.5:  # 50%的概率添加序号
            title += f" #{i+1}"
        
        # 生成描述
        description = fake.text(max_nb_chars=200)
        
        # 选择标签
        available_tags = common_tags[category]
        tag_count = random.randint(1, 4)
        tags = random.sample(available_tags, min(tag_count, len(available_tags)))
        
        # 生成文件URL（模拟）
        file_extensions = {
            "image": [".jpg", ".png", ".gif"],
            "video": [".mp4", ".avi", ".mov"],
            "music": [".mp3", ".wav", ".aac"],
            "text": [".txt", ".pdf", ".docx"]
        }
        
        ext = random.choice(file_extensions[category])
        filename = f"{category}_{i+1:03d}_{uuid.uuid4().hex[:8]}{ext}"
        file_url = f"/uploads/works/{filename}"
        
        # 图片和视频有缩略图
        thumbnail = None
        if category in ["image", "video"]:
            thumb_filename = f"thumb_{filename.replace(ext, '.jpg')}"
            thumbnail = f"/uploads/thumbnails/{thumb_filename}"
        
        # 随机生成统计数据
        views = random.randint(0, 5000)
        likes = random.randint(0, min(views // 10, 500))
        comments = random.randint(0, min(likes // 5, 100))
        
        # 随机创建时间（最近3个月内）
        days_ago = random.randint(0, 90)
        created_at = datetime.now() - timedelta(days=days_ago)
        
        work = Work(
            title=title,
            description=description,
            category=category,
            tags=tags,
            file_url=file_url,
            thumbnail=thumbnail,
            file_size=random.randint(1024, 10485760),  # 1KB - 10MB
            mime_type=f"{category}/{'jpeg' if category == 'image' else 'mp4' if category == 'video' else 'mp3' if category == 'music' else 'plain'}",
            views=views,
            likes=likes,
            comments=comments,
            user_id=user.id,
            created_at=created_at
        )
        
        works.append(work)
    
    # 批量添加到数据库
    db.add_all(works)
    db.commit()
    
    print(f"成功创建 {len(works)} 个作品")
    return works

def create_sample_contests(db: Session, count: int = 15):
    """
    创建示例竞赛
    
    Args:
        db: 数据库会话
        count: 创建竞赛数量
    """
    print(f"正在创建 {count} 个示例竞赛...")
    
    # 竞赛标题模板
    contest_titles = [
        "我心中的岳阳楼-科技与文化交织的千年华章-AIGC短视频创作大赛",
        "AI绘画创意大赛",
        "智能音乐创作挑战赛",
        "未来城市设计竞赛",
        "AI写作马拉松",
        "数字艺术创新大赛",
        "机器学习应用竞赛",
        "创意视频制作大赛",
        "人工智能诗歌创作赛",
        "虚拟现实体验设计赛",
        "智能交互设计挑战",
        "AI辅助教育创新赛",
        "可持续发展创意赛",
        "科技与艺术融合赛",
        "青年创新创业大赛"
    ]
    
    # 主办方列表
    organizers = [
        "中国人工智能学会",
        "教育部高等教育司",
        "科技部火炬中心",
        "中国计算机学会",
        "清华大学",
        "北京大学",
        "中科院计算所",
        "腾讯AI Lab",
        "百度研究院",
        "阿里巴巴达摩院"
    ]
    
    categories = ["video", "image", "music", "text"]
    
    contests = []
    
    for i in range(count):
        title = contest_titles[i] if i < len(contest_titles) else f"AI创作大赛 #{i+1}"
        
        # 生成竞赛时间
        if i < 5:  # 前5个是已结束的竞赛
            start_date = fake.date_between(start_date='-6m', end_date='-2m')
            end_date = start_date + timedelta(days=random.randint(30, 90))
            status = "ended"
            participant_count = random.randint(500, 3000)
        elif i < 10:  # 中间5个是进行中的竞赛
            start_date = fake.date_between(start_date='-1m', end_date='today')
            end_date = start_date + timedelta(days=random.randint(30, 90))
            status = "ongoing"
            participant_count = random.randint(100, 1500)
        else:  # 后面的是即将开始的竞赛
            start_date = fake.date_between(start_date='today', end_date='+3m')
            end_date = start_date + timedelta(days=random.randint(30, 90))
            status = "upcoming"
            participant_count = random.randint(0, 200)
        
        # 生成描述和规则
        description = fake.text(max_nb_chars=500)
        rules = f"""1. 参赛作品必须为原创作品，不得抄袭或侵犯他人知识产权。
2. 作品主题需符合竞赛要求，内容积极向上。
3. 参赛者需在规定时间内提交完整作品。
4. 评审将从创意性、技术性、艺术性等多个维度进行评分。
5. 获奖作品将有机会在相关平台展示推广。
6. 主办方拥有获奖作品的展示权和推广权。
7. 参赛即视为同意本竞赛规则和相关条款。"""
        
        # 奖金信息
        prizes = [
            "一等奖：10000元 + 证书",
            "一等奖：50000元 + 证书 + 实习机会",
            "一等奖：20000元 + 证书 + 专业指导",
            "一等奖：30000元 + 证书 + 展示机会"
        ]
        prize = random.choice(prizes)
        
        contest = Contest(
            title=title,
            description=description,
            rules=rules,
            start_date=start_date,
            end_date=end_date,
            status=status,
            prize=prize,
            organizer=random.choice(organizers),
            category=random.choice(categories),
            participant_count=participant_count,
            created_at=datetime.now() - timedelta(days=random.randint(0, 180))
        )
        
        contests.append(contest)
    
    # 批量添加到数据库
    db.add_all(contests)
    db.commit()
    
    print(f"成功创建 {len(contests)} 个竞赛")
    return contests

def create_sample_ai_tools(db: Session, count: int = 50):
    """
    创建示例AI工具
    
    Args:
        db: 数据库会话
        count: 创建工具数量
    """
    print(f"正在创建 {count} 个示例AI工具...")
    
    # AI工具数据
    ai_tools_data = [
        {
            "name": "ChatGPT",
            "description": "强大的AI对话助手，能够回答问题、写作、编程等",
            "category": "对话",
            "tags": ["对话", "写作", "编程", "问答"],
            "url": "https://chat.openai.com",
            "rating": 48,
            "popularity": 9500
        },
        {
            "name": "Midjourney",
            "description": "AI图像生成工具，可以根据文字描述生成高质量的艺术作品",
            "category": "图像生成",
            "tags": ["图像生成", "艺术", "设计", "创意"],
            "url": "https://midjourney.com",
            "rating": 46,
            "popularity": 8200
        },
        {
            "name": "Stable Diffusion",
            "description": "开源的AI图像生成模型，支持本地部署和自定义训练",
            "category": "图像生成",
            "tags": ["图像生成", "开源", "本地部署", "自定义"],
            "url": "https://stability.ai",
            "rating": 44,
            "popularity": 7800
        },
        {
            "name": "Claude",
            "description": "Anthropic开发的AI助手，擅长分析、写作和对话",
            "category": "对话",
            "tags": ["对话", "分析", "写作", "助手"],
            "url": "https://claude.ai",
            "rating": 45,
            "popularity": 6500
        },
        {
            "name": "文心一言",
            "description": "百度开发的中文AI对话系统，支持多轮对话和内容生成",
            "category": "对话",
            "tags": ["中文", "对话", "内容生成", "百度"],
            "url": "https://yiyan.baidu.com",
            "rating": 42,
            "popularity": 5200
        },
        {
            "name": "DALL-E 3",
            "description": "OpenAI的最新图像生成模型，能够生成高质量、高精度的图像",
            "category": "图像生成",
            "tags": ["图像生成", "OpenAI", "高质量", "精确"],
            "url": "https://openai.com/dall-e-3",
            "rating": 47,
            "popularity": 7200
        },
        {
            "name": "GitHub Copilot",
            "description": "AI编程助手，能够根据注释和代码上下文自动生成代码",
            "category": "编程",
            "tags": ["编程", "代码生成", "GitHub", "开发"],
            "url": "https://github.com/features/copilot",
            "rating": 43,
            "popularity": 6800
        },
        {
            "name": "Runway ML",
            "description": "AI视频编辑和生成工具，支持视频特效和内容创作",
            "category": "视频",
            "tags": ["视频编辑", "视频生成", "特效", "创作"],
            "url": "https://runwayml.com",
            "rating": 41,
            "popularity": 4500
        },
        {
            "name": "Notion AI",
            "description": "集成在Notion中的AI写作助手，帮助用户提高写作效率",
            "category": "写作",
            "tags": ["写作", "笔记", "效率", "助手"],
            "url": "https://notion.so/ai",
            "rating": 40,
            "popularity": 3800
        },
        {
            "name": "Mubert",
            "description": "AI音乐生成平台，可以根据情绪和场景生成背景音乐",
            "category": "音乐",
            "tags": ["音乐生成", "背景音乐", "情绪", "场景"],
            "url": "https://mubert.com",
            "rating": 38,
            "popularity": 2200
        }
    ]
    
    # 扩展更多工具
    categories = ["对话", "图像生成", "视频", "音乐", "编程", "写作", "翻译", "设计"]
    
    tools = []
    
    # 添加预定义的工具
    for tool_data in ai_tools_data:
        tool = AITool(
            name=tool_data["name"],
            description=tool_data["description"],
            icon=f"/img/tools/{tool_data['name'].lower().replace(' ', '_')}.png",
            url=tool_data["url"],
            category=tool_data["category"],
            tags=tool_data["tags"],
            rating=tool_data["rating"],
            popularity=tool_data["popularity"],
            is_active=True
        )
        tools.append(tool)
    
    # 生成更多随机工具
    for i in range(count - len(ai_tools_data)):
        category = random.choice(categories)
        name = f"AI工具 {i+1:02d}"
        
        tool = AITool(
            name=name,
            description=fake.text(max_nb_chars=150),
            icon=f"/img/tools/tool_{i+1:02d}.png",
            url=f"https://example-ai-tool-{i+1}.com",
            category=category,
            tags=random.sample(["AI", "智能", "自动化", "效率", "创意", "技术"], k=random.randint(2, 4)),
            rating=random.randint(25, 50),  # 2.5-5.0分
            popularity=random.randint(100, 5000),
            is_active=True
        )
        tools.append(tool)
    
    # 批量添加到数据库
    db.add_all(tools)
    db.commit()
    
    print(f"成功创建 {len(tools)} 个AI工具")
    return tools

def main():
    """
    主函数：初始化数据库并创建示例数据
    """
    print("=" * 50)
    print("AI HUB 数据库初始化脚本")
    print("=" * 50)
    
    # 询问是否重置数据库
    if len(sys.argv) > 1 and sys.argv[1] == "--reset":
        confirm = input("确定要重置数据库吗？这将删除所有现有数据！(y/N): ")
        if confirm.lower() == 'y':
            print("正在重置数据库...")
            reset_db()
        else:
            print("取消重置，退出程序")
            return
    else:
        print("正在初始化数据库...")
        init_db()
    
    # 创建数据库会话
    db = SessionLocal()
    
    try:
        # 创建示例数据
        users = create_sample_users(db, count=20)
        works = create_sample_works(db, users, count=100)
        contests = create_sample_contests(db, count=15)
        ai_tools = create_sample_ai_tools(db, count=50)
        
        print("\n" + "=" * 50)
        print("数据库初始化完成！")
        print(f"创建用户: {len(users)} 个")
        print(f"创建作品: {len(works)} 个")
        print(f"创建竞赛: {len(contests)} 个")
        print(f"创建AI工具: {len(ai_tools)} 个")
        print("=" * 50)
        
        print("\n测试账号信息:")
        print("管理员账号: admin / admin123")
        print("测试账号: testuser / test123")
        print("\n可以使用这些账号登录系统进行测试")
        
    except Exception as e:
        print(f"创建示例数据时出错: {e}")
        db.rollback()
    finally:
        db.close()

if __name__ == "__main__":
    main()